package tp.pr4.instructions;

import java.util.StringTokenizer;

import tp.pr4.Direction;
import tp.pr4.NavigationModule;
import tp.pr4.RobotEngine;
import tp.pr4.Rotation;
import tp.pr4.instructions.exceptions.InstructionExecutionException;
import tp.pr4.instructions.exceptions.WrongInstructionFormatException;
import tp.pr4.items.ItemContainer;

public class TurnInstruction
extends java.lang.Object
implements Instruction {
	
	private NavigationModule navigation;
	private Rotation rotation;
	private RobotEngine engine;
	
	public Instruction parse(java.lang.String cad) throws WrongInstructionFormatException
	{
		StringTokenizer instructionToken = new StringTokenizer(cad);
	    if(instructionToken.countTokens()!=2) 
			throw new WrongInstructionFormatException();
		
		String action=instructionToken.nextToken();
		if (!(action.toUpperCase().equalsIgnoreCase("TURN") || action.toUpperCase().equalsIgnoreCase("GIRAR")))
			throw new WrongInstructionFormatException();
		
		String rotationString=instructionToken.nextToken();
		if (!(rotationString.toUpperCase().equalsIgnoreCase("LEFT") || rotationString.toUpperCase().equalsIgnoreCase("RIGHT")))
			throw new WrongInstructionFormatException();		
		
		this.rotation=Rotation.valueOf(rotationString.toUpperCase());
		
		return this;		
	}
	
	public void execute() throws InstructionExecutionException
	{
		try
		{
		navigation.initHeading(Direction.rotate(navigation.getCurrentHeading(), rotation));
		engine.addFuel(-5);		
		System.out.println("WALL·E is looking at direction " + navigation.getCurrentHeading());
		engine.printRobotState();
		}catch(Exception e){
			throw new InstructionExecutionException(e);
		}	
	}
	
	
	public java.lang.String getHelp()
	{
		return ("TURN | GIRAR < LEFT|RIGHT >");
	}
	
	public void configureContext(RobotEngine engine,
            NavigationModule navigation,
            ItemContainer robotContainer)
	{
		this.navigation=navigation;
		this.engine=engine;
	}

}
